package top.yj95.xiets.basic;

import java.awt.event.ItemEvent;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.WindowConstants;

/**
 * 文章《<a href="https://xiets.blog.csdn.net/article/details/74363699" target="_balnk">JavaSwing_2.9: JComboBox（下拉列表框）</a>》中的示例代码
 * @author 杨军
 * @since 2023-12-22
 */
public class JComboBoxDemo {

    public static void main(String[] args) {
        JFrame frame = new JFrame("测试窗口");
        frame.setSize(250, 200);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        
        JPanel panel = new JPanel();
        
        // 添加一个标签
        JLabel label = new JLabel("水果：");
        panel.add(label);
        
        // 需要选择的条目
        String[] listData = { "香蕉", "雪梨", "苹果", "荔枝" };
        
        // 创建一个下拉列表框
        JComboBox<String> comboBox = new JComboBox<>(listData);
        
        // 添加条目选中状态改变的监听器
        comboBox.addItemListener(e -> {
            if (e.getStateChange() == ItemEvent.SELECTED) { // 只处理选中的状态
                System.out.printf("选中：%d = %s\n", comboBox.getSelectedIndex(), comboBox.getSelectedItem());
            }
        });
        
        // 设置默认选中的条目
        comboBox.setSelectedIndex(2);
        
        // 添加到内容面板
        panel.add(comboBox);
        
        frame.setContentPane(panel);
        frame.setVisible(true);
    }
    
}
